<template>
	<el-card>
		<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
			<el-form-item>
				<el-input v-model="state.queryForm.deviceId" placeholder="设备ID"></el-input>
			</el-form-item>
			<el-form-item>
				<el-input v-model="state.queryForm.deviceTemperature" placeholder="设备温度"></el-input>
			</el-form-item>
			<el-form-item>
				<el-input v-model="state.queryForm.deviceHumidity" placeholder="设备湿度"></el-input>
			</el-form-item>
			<el-form-item>
				<el-input v-model="state.queryForm.deviceBrightness" placeholder="设备亮度"></el-input>
			</el-form-item>
			<el-form-item>
				<el-input v-model="state.queryForm.deviceStatus" placeholder="设备状态"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button @click="getDataList()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
			</el-form-item>
			<el-form-item>
				<el-button type="danger" @click="deleteBatchHandle()">删除</el-button>
			</el-form-item>
			<el-form-item>
				<el-button @click="changeView()">视图切换</el-button>
			</el-form-item>
		</el-form>
		<div v-show="!viewValue" class="history_tab">
			<el-table v-loading="state.dataListLoading" :data="state.dataList" border style="width: 100%"
				@selection-change="selectionChangeHandle">
				<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
				<el-table-column label="序号" header-align="center" align="center">
					<template #default="scope">
						{{ scope.row.index + 1 }}
					</template>
				</el-table-column>
				<!--			<el-table-column prop="deviceStatusId" label="设备状态ID" header-align="center" align="center"></el-table-column>-->
				<el-table-column prop="deviceId" label="设备ID" header-align="center" align="center"></el-table-column>
				<el-table-column prop="deviceTemperature" label="设备温度" header-align="center"
					align="center"></el-table-column>
				<el-table-column prop="deviceHumidity" label="设备湿度" header-align="center" align="center"></el-table-column>
				<el-table-column prop="deviceBrightness" label="设备亮度" header-align="center"
					align="center"></el-table-column>
				<el-table-column prop="deviceStatus" label="设备状态" header-align="center" align="center"
					:formatter="formatSuperAdmin"> </el-table-column>
				<!--      deviceIntoTime 设备入库时间-->
				<el-table-column prop="deviceIntoTime" show-overflow-tooltip label="设备入库时间" header-align="center"
					align="center"></el-table-column>
				<el-table-column label="操作" fixed="right" header-align="center" align="center" width="270">
					<template #default="scope">
						<el-button v-auth="'sys:menu:update'" type="primary" link
							@click="addOrUpdateHandle(scope.row.deviceStatusId)">修改</el-button>
						<el-button v-auth="'sys:menu:delete'" type="primary" link
							@click="deleteById(scope.row.deviceStatusId)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination :current-page="state.page" :page-sizes="state.pageSizes" :page-size="state.limit"
				:total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="sizeChangeHandle"
				@current-change="currentChangeHandle">
			</el-pagination>
			<!-- 弹窗, 新增 / 修改 -->
			<add-or-update ref="addOrUpdateRef" @refreshDataList="getDataList"></add-or-update>
		</div>
		<div v-show="viewValue" class="history_echarts">
			<div>
				<div style="display: flex; margin: 20px 0">
					<div style="width: 50%;" class="card">
						<div ref="temperatureChart" style="width: 100%; height: 400px;"></div>
					</div>
					<div style="width: 50%;" class="card">
						<div ref="humidityChart" style="width: 100%; height: 400px;"></div>
					</div>
				</div>

				<div style="display: flex; margin: 10px 0">
					<div style="width: 50%;" class="card">
						<div ref="catTemperatureChart" style="width: 100%; height: 400px;"></div>
					</div>
					<div style="width: 50%;" class="card">
						<div ref="lightIntensityChart" style="width: 100%; height: 400px;"></div>
					</div>
				</div>
			</div>
		</div>
	</el-card>
</template>

<script setup lang="ts" name="ClouddeviceStatusIndex">
import { useCrud } from '@/hooks'
import { onMounted, reactive, ref, nextTick } from 'vue'
import AddOrUpdate from './add-or-update.vue'
import { IHooksOptions } from '@/hooks/interface'
import service from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'

const state: IHooksOptions = reactive({
	dataListUrl: 'deviceStatus/queryPage',
	deleteUrl: '/deviceStatus/deleteById',
	queryForm: {
		deviceStatusId: '',
		deviceId: '',
		deviceTemperature: '',
		deviceHumidity: '',
		deviceBrightness: '',
		deviceStatus: ''
	}
})

const formatSuperAdmin = (row: any) => {
	return row.deviceStatus === 0 ? '正常' : '异常'
}
const addOrUpdateRef = ref()
const addOrUpdateHandle = (id?: number) => {
	state.queryForm.deviceStatusId = id
	addOrUpdateRef.value.init(JSON.stringify(state.queryForm))
	state.queryForm.deviceStatusId = ''
}
const deleteById = (id: any) => {
	const data = { deviceStatusId: id, isDel: 1 }
	// service.post('/device/deleteById', device)
	ElMessageBox.confirm('确定进行删除操作?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			if (state.deleteUrl) {
				console.log('点击删除')
				service.post(state.deleteUrl, data).then(() => {
					ElMessage.success('删除成功')

					getDataList()
				})
			}
		})
		.catch(() => { })
}

//视图切换
//视图参数
const viewValue = ref(true)
const changeView = () => {
	getDataList()
	viewValue.value = !viewValue.value;
	if (viewValue.value) {
		initializeCharts(); // Initialize charts only when switching to the chart view
	}
};
// Refs for chart elements
const temperatureChart = ref<HTMLElement | null>(null);
const humidityChart = ref(null);
const catTemperatureChart = ref<HTMLElement | null>(null);
const lightIntensityChart = ref<HTMLElement | null>(null);


const initializeCharts = () => {
	let deviceIntoTimeList: any[] = [];

	service
		.get('deviceStatus/queryPage', {
			params: {
				order: state.order,
				asc: state.asc,
				page: state.isPage ? state.page : null,
				limit: state.isPage ? state.limit : null,
				...state.queryForm
			}
		})
		.then((res) => {
			state.dataList = state.isPage ? res.data.records : res.data;
			deviceIntoTimeList = state.dataList.map((item: any) => item.deviceIntoTime);
			const deviceTemperatureList = state.dataList.map((item: any) => item.deviceTemperature);
			const deviceHumidityList = state.dataList.map((item: any) => item.deviceHumidity);
			const deviceBrightnessList = state.dataList.map((item: any) => item.deviceBrightness);
			const deviceStatusList = state.dataList.map((item: any) => item.deviceStatus);

			console.log("打印初始化渲染的数据", deviceIntoTimeList);
			if (temperatureChart.value) {
				const chart = echarts.init(temperatureChart.value);
				chart.setOption({
					title: {
						text: '历史温度'
					},
					xAxis: {
						type: 'category',
						data: deviceIntoTimeList
					},
					yAxis: {
						type: 'value'
					},
					series: [{
						data: deviceTemperatureList,
						type: 'line'
					}]
				});
			}

			if (humidityChart.value) {
				const chart = echarts.init(humidityChart.value);
				chart?.setOption({
					title: {
						text: '历史湿度'
					},
					xAxis: {
						type: 'category',
						data: deviceIntoTimeList
					},
					yAxis: {
						type: 'value'
					},
					series: [{
						data: deviceHumidityList,
						type: 'line'
					}]
				});
			}

			if (catTemperatureChart.value) {
				const chart = echarts.init(catTemperatureChart.value);
				chart.setOption({
					title: {
						text: '历史亮度'
					},
					xAxis: {
						type: 'category',
						data: deviceIntoTimeList
					},
					yAxis: {
						type: 'value'
					},
					series: [{
						data: deviceBrightnessList,
						type: 'line'
					}]
				});
			}

			if (lightIntensityChart.value) {
				const chart = echarts.init(lightIntensityChart.value);
				chart.setOption({
					title: {
						text: '历史设备状态'
					},
					xAxis: {
						type: 'category',
						data: deviceIntoTimeList
					},
					yAxis: {
						type: 'category',
						data: ['正常', '异常']
					},
					series: [{
						data: deviceStatusList.map(status => status === 0 ? '正常' : '异常'),
						type: 'line'
					}]
				});
			}
		})
		.catch((error) => {
			console.error('Error fetching data:', error);
		});

	console.log("打印设备时间集合", deviceIntoTimeList);
};
onMounted(() => {
	nextTick(() => {
		initializeCharts()
	})
})
const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteBatchHandle } = useCrud(state)
</script>
